package com.loto.insurance.mis.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.loto.insurance.mis.web.db.mapper.UserInfoMapper;
import com.loto.insurance.mis.web.db.mapper.UserLoginLogMapper;
import com.loto.insurance.mis.web.entity.UserInfo;
import com.loto.insurance.mis.web.entity.SessionUser;
import com.loto.insurance.mis.web.entity.UserLoginLog;
import com.loto.insurance.mis.web.entity.ajax.BaseJson;
import com.loto.insurance.mis.web.enumeration.ControllerPropertyEnum;
import com.loto.insurance.mis.web.utils.Config;
import com.loto.insurance.mis.web.utils.WebUtils;
import com.loto.utils.MD5;

@Service
public class UserInfoService {
  @Autowired
  UserInfoMapper userInfoMapper;

  @Autowired
  UserLoginLogMapper userLoginLogMapper;

  public BaseJson doLogin(HttpServletRequest request, String loginName,
	  String loginPwd) {
	BaseJson base = new BaseJson();
	base.setOk(false);
	base.setMsg(ControllerPropertyEnum.WRONG_USERNAME.toString());
	UserInfo userInfo = userInfoMapper.findActiveByName(loginName);
	String pwd = userInfo.getUserPwd();
	if (pwd != null && !pwd.isEmpty()) {
	  if (pwd.toLowerCase().equals(MD5.GetMD5Code(loginPwd).toLowerCase())) {
		// session
		SessionUser user = new SessionUser();
		user.setUserId(userInfo.getUserId());
		user.setUsername(userInfo.getUserName());
		user.setRoleIds(userInfo.getUserRoleFids());
		HttpSession session = request.getSession();
		session.setAttribute("ins_user", user);

		// 登录日志
		UserLoginLog loginLog = new UserLoginLog();
		loginLog.setLogCreatedBy(userInfo.getUserId());
		loginLog.setLogIp(WebUtils.getIpAddr(request));
		userLoginLogMapper.insertLog(loginLog);

		base.setOk(true);
		base.setMsg("");
	  }
	}
	return base;
  }

  public boolean addUser(UserInfo userInfo, ArrayList<String> menuList) {
	Config c = new Config();
	return c.updateMenuConfigFile(userInfo.getUserName(), menuList)
	    && userInfoMapper.insertUser(userInfo) > 0;
  }

  public boolean updateUser(UserInfo userInfo, ArrayList<String> menuList) {
	Config c = new Config();
	UserInfo uInfo=userInfoMapper.findUserById(userInfo.getUserId());
	return c.updateMenuConfigFile(uInfo.getUserName(), menuList)
	    && userInfoMapper.updateUser(userInfo) > 0;
  }

  public UserInfo findUserById(long userId) {
	return userInfoMapper.findUserById(userId);
  }

  public UserInfo findUserByName(String userName) {
	return userInfoMapper.findUserByName(userName);
  }

  public long findAllUserCount(Map<String, Object> params) {
	return userInfoMapper.findAllUserPagerCount(params);
  }

  public List<UserInfo> findAllUser(Map<String, Object> params) {
	return userInfoMapper.findAllUserPager(params);
  }
}
